package yl.hs.bmipfull.service.production.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import yl.hs.bmipfull.daos.laboratory.IPackageInfoDao;
import yl.hs.bmipfull.daos.laboratory.IProductCateDao;
import yl.hs.bmipfull.daos.laboratory.IProductInfoDao;
import yl.hs.bmipfull.daos.laboratory.IProductOverageDao;
import yl.hs.bmipfull.daos.material.*;
import yl.hs.bmipfull.daos.production.*;
import yl.hs.bmipfull.daos.salemanage.*;
import yl.hs.bmipfull.daos.system.IAppSettingDao;
import yl.hs.bmipfull.daos.system.IDictItemDao;
import yl.hs.bmipfull.daos.system.IWechatUserDao;
import yl.hs.bmipfull.daos.vehiclemanage.ITruckInfoDao;
import yl.hs.bmipfull.pojo.customize.ProductionTaskCumulative;
import yl.hs.bmipfull.pojo.material.PurchaseReceiptEntity;
import yl.hs.bmipfull.pojo.material.RawMaterialInventoryEntity;
import yl.hs.bmipfull.pojo.production.BrickShipOrderDetailEntity;
import yl.hs.bmipfull.pojo.production.BrickShipOrderEntity;
import yl.hs.bmipfull.pojo.production.ProductShipOrderEntity;
import yl.hs.bmipfull.pojo.production.TransTaskEntity;
import yl.hs.bmipfull.pojo.salemanage.SaleOrderPlaceDetailEntity;
import yl.hs.bmipfull.service.production.IWeightService;
import yl.hs.bmipfull.utils.CK;
import yl.hs.bmipfull.utils.HsApp;
import yl.hs.bmipfull.utils.Tl;
import yl.hs.bmipfull.utils.datastate.ActionType;
import yl.hs.bmipfull.utils.datastate.MsgReceiveType;
import yl.hs.bmipfull.utils.datastate.MsgType;
import yl.hs.bmipfull.viewmodels.WeightApp.WeightData;
import yl.hs.bmipfull.viewmodels.finance.OrderState;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/*
 * WeightServiceImpl
 * @category
 * @author 谢景广
 * @date 2022-04-13
 */
@Service
@Slf4j
public class WeightServiceImpl extends ProductionBaseService implements IWeightService {

    @Autowired
    IProductShipOrderDao shipDAO;

    @Autowired
    IPurchaseReceiptDao receiptDao;
    @Autowired
    IWechatUserDao wechatDao;

    @Autowired
    ISupplierDao supplierDao;

    @Autowired
    IRawMaterialInfoDao rmDao;

    @Autowired
    IRawMaterialCateDao rmCateDao;

    @Autowired
    IRawMaterialInventoryDao inventoryDao;

    @Autowired
    IProductCateDao productCateDao;

    @Autowired
    IProductOverageDao overageDao;

    @Autowired
    ITransTaskDao transTaskDao;

    @Autowired
    IProductInfoDao productDao;

    @Autowired
    IProductionTaskDao proTaskDao;

    @Autowired
    ISaleContractDao contractDao;

    @Autowired
    IContractControlInfoDao controlInfoDao;

    @Autowired
    IProductionLineDao proLineDao;

    @Autowired
    ISaleContractProductsDao conProDao;

    @Autowired
    ILinkerInfoDao linkerDao;
    @Autowired
    IDictItemDao itemDao;
    @Autowired
    IAppSettingDao appSetDao;
    @Autowired
    ITruckInfoDao cardao;
    @Autowired
    IPackageInfoDao packageInfoDao;
    @Autowired
    ICustomerInfoDao customerInfoDao;
    @Autowired
    IPurchaseContractDao purchaseContractDao;
    @Autowired
    IWarehouseDao warehouseDao;
    @Autowired
    ISaleOrderPlaceDao placeDao;
    @Autowired
    IBrickShipOrderDao brickShipOrderDao;
    @Autowired
    IBrickShipOrderDetailDao brickShipOrderDetailDao;
    @Autowired
    ISaleContractDao saleContractDao;
    @Autowired
    ISaleOrderPlaceDetailDao detailDao;

    private List<ProductShipOrderEntity> createOrderByTransTask(List<TransTaskEntity> taskList, BigDecimal weight,
                                                                BigDecimal orgWeight, ProductShipOrderEntity order) throws Exception {
        var orderList = new ArrayList<ProductShipOrderEntity>();
        //var mergeSN = queryNewSN(ProductShipOrderEntity.class);
        for (var i = 0; i < 1; i++) {
            var task = taskList.get(0);
            var productCate = productCateDao.findBySN(task.getProductCateSN());
            if (productCate == null) {
                throw new Exception("派车信息关联的产品类别未找到");
            }
            var proTask = proTaskDao.findBySN(task.getProductionTaskSN());
            if (proTask == null) {
                throw new Exception("派车信息关联的生产任务未找到");
            }
            var controlList = controlInfoDao.queryByContractSn(proTask.getContractSN());
            //var order = new ProductShipOrderEntity();
            order.setTaskSN(proTask.getSn());
            order.setBillProductName(proTask.getBillProductName());
            order.setBillProductSN(proTask.getBillProductSN());
            order.setBillProductSpec(proTask.getBillProductSpec());
            order.setAccountProductName(proTask.getAccountProductName() == null ? "" : proTask.getAccountProductName());
            order.setAccountProductSN(proTask.getAccountProductSN() == null ? "" : proTask.getAccountProductSN());
            order.setAccountProductSpec(proTask.getAccountProductSpec() == null ? "" : proTask.getAccountProductSpec());
            if ((proTask.getPackageWeight() == null ? BigDecimal.ZERO : proTask.getPackageWeight()).compareTo(BigDecimal.valueOf(1)) > 0) {
                order.setOrderType((short) 1);
            } else {
                order.setOrderType((short) 0);
            }
            var truck = cardao.findBySN(task.getTruckSN());
            if (truck != null) {
                order.setTruckCode(truck.getTruckCode());
                order.setTruckPlate(truck.getTruckPlate());
                order.setTruckSN(truck.getSn());
                order.setDriverSN(truck.getDriverSN());
                order.setDriverName(truck.getDriverName());
            }
            //order.setOrderType(proTask.getTaskType());
            //计算方量，并追加虚方数
            var netWeight = weight.subtract(order.getTareWeight());
            if (task.getTransType() == 0) {
                var sj = HsApp.getSystemSet(CK.Sjzf) == null ? BigDecimal.valueOf(1.2) : new BigDecimal(HsApp.getSystemSet(CK.Sjzf));
                var weights = netWeight.subtract(task.getAppendWeight().multiply(sj));
                var query = weights.divide((proTask.getDensity() == null ? BigDecimal.valueOf(1) : proTask.getDensity()), 2, RoundingMode.HALF_UP).add(proTask.getVirtualQuantity() == null ? BigDecimal.valueOf(0.00) : proTask.getVirtualQuantity());
                order.setQuantity(query.add(task.getAppendWeight()));
            } else {
                order.setQuantity(netWeight.divide((proTask.getDensity() == null ? BigDecimal.valueOf(1) : proTask.getDensity()), 2, RoundingMode.HALF_UP).add(proTask.getVirtualQuantity() == null ? BigDecimal.valueOf(0.00) : proTask.getVirtualQuantity()));
            }
            order.setGrossWeight(weight.add(proTask.getVirtualQuantity() == null ? BigDecimal.valueOf(0.00) : proTask.getVirtualQuantity()));
            order.setOrgGrossWeight(orgWeight);
            order.setTareWeight(order.getTareWeight());
            order.setNetWeight(netWeight.add(proTask.getVirtualQuantity() == null ? BigDecimal.valueOf(0.00) : proTask.getVirtualQuantity()));
            order.setVirtualQuantity(proTask.getVirtualQuantity());
            //}
            order.setAppendWeight(task.getAppendWeight());
            order.setPackUnit(proTask.getPackUnit());
            order.setPackWay(proTask.getPackageWay());
            order.setPackWeight(proTask.getPackageWeight());
            var ss = order.getQuantity().subtract((BigDecimal) task.getSaleWeight());
            var line = proLineDao.findBySN(task.getProductionLineSN());
            if (ss.compareTo(BigDecimal.valueOf(0.2)) > 0 || ss.compareTo(BigDecimal.valueOf(-0.2)) < 0) {
                sendMsg(MsgType.Bulletin, MsgReceiveType.Role, "ROLE221014000011,ROLE221014000013,ROLE221014000012,ROLE221014000014,ROLE221014000019,ROLE221014000021", "过磅误差提醒", "发货单编号:" + order.getSn() + ",生产线:" + line.getPlName() + ",车辆:" + order.getTruckCode() + "过磅方量为:" + order.getQuantity() + "(方)，派车方量为:" + task.getSaleWeight() + "(方)，误差为" + ss + "(方),请注意！");
            }
            //合同控制处理
            if (controlList.size() > 0) {
                var controlFlag = false;
                var message = "";
                for (var control : controlList) {
                    var min = control.getStartTime();
                    switch (control.getControlType()) {
                        case (short) 1://天数控制
                            Calendar dt = Calendar.getInstance();
                            dt.setTime(min);
                            dt.add(Calendar.DATE, (int) control.getDisabValue());
                            if ((new Date()).compareTo(dt.getTime()) > 0) {
                                controlFlag = true;
                                message = "已超过合同发货天数控制，禁止发货";
                            }
                            break;
                        case (short) 2:
                            var shipAmount = shipDAO.getControlShipAmountCount(control.getContractSN(), min);
                            //加上本车金额
                            shipAmount = shipAmount.add(order.getQuantity().multiply(shipDAO.getProductPrice(control.getContractSN(), proTask.getProductSN(), new Date(), proTask.getProductionParam())));
                            if (shipAmount.compareTo(new BigDecimal(control.getDisabValue())) >= 0) {
                                controlFlag = true;
                                message = "已超过合同发货金额控制，禁止发货";
                            }
                            break;
                        case (short) 3:
                            var shipQuantity = shipDAO.getControlShipQuantityCount(control.getContractSN(), min);
                            shipQuantity = shipQuantity.add(order.getQuantity());
                            if (shipQuantity.compareTo(new BigDecimal(control.getDisabValue())) >= 0) {
                                controlFlag = true;
                                message = "已超过合同发货数量控制，禁止发货";
                            }
                            break;
                    }
                    if (controlFlag) {
                        break;
                    }
                }
                if (controlFlag) {
                    throw new Exception(message);
                }
            }
            var contract = contractDao.findBySN(proTask.getContractSN());
            if (contract != null) {
                var customer = customerInfoDao.findBySN(contract.getCustomerSN());
                if (customer != null) {
                    order.setCustomerSN(customer.getSn());
                    order.setCustomerName(customer.getCustName());
                    order.setCustomerNamePY(customer.getCustNamePY());
                    order.setContractingUnit(contract.getContractingUnit());
                }
            }
            //order.setMergeSN(mergeSN);
            if (!Tl.isEmpty(task.getProductionLineSN())) {
                var proLine = proLineDao.findBySN(task.getProductionLineSN());
                order.setLineSN(task.getProductionLineSN());
                order.setProductLineName(proLine != null ? proLine.getPlName() : "");
            }

            //order.setSn(mergeSN);
            order.setProductCateSN(task.getProductCateSN());
            order.setProductCate(productCate.getCateName());
            ProductionTaskCumulative cumulative = shipDAO.getProTaskCumulative(task.getProductionTaskSN());
            if (cumulative == null) {
                order.setCumulativeTrucks(1);
                order.setCumulativeQuantity(order.getQuantity());
            } else {
                order.setCumulativeTrucks(cumulative.getTrucks() + 1);
                order.setCumulativeQuantity(cumulative.getQuantity().add(order.getQuantity()));
            }
            order.setProductSN(task.getProductSN());
            var product = productDao.findBySN(task.getProductSN());
            order.setProductSpec(product.getProductSpec());
            order.setProductTags(proTask.getProductionParam() == null ? "" : proTask.getProductionParam());
            order.setProductName(proTask.getProductName());
            order.setOrganizationCode(proTask.getOrganizationCode());
            order.setAddress(proTask.getProjectAddr());
            order.setCustomerSN(contract.getCustomerSN());
            order.setContractSN(proTask.getContractSN());
            order.setProjectName(proTask.getProjectName());
            order.setDensity(proTask.getDensity());
            order.setBuildPosition(proTask.getPosition() == null ? "" : proTask.getPosition());
            order.setSalerName(proTask.getSalerName());
            order.setSalePhone(proTask.getSalerPhone());
            order.setSalesVolume(task.getSaleWeight());
            order.setLinkePhone(proTask.getProjectPhone());
            order.setLinkerName(proTask.getProjectLinker());
            order.setOutTime(new Date());
            order.setPrintTitle(CK.Weather);
            order.setRemark(proTask.getRemark());
            order.setState((short) 1);
            order.setPYFieldValue();
            order.setHandlerName("无人值守");
            //if (productCate.isPackageEnable()) {
            var paramMap = Tl.parseTaskParam(proTask.getProductionParam());
            if (Tl.getInteger(paramMap.get("productionMode"), 0) == 2) {//库存发货
                inventoryDao.subsideInventory(paramMap.get("warehouse"), order.getProductSN(), order.getQuantity());
            }
            //}
            // shipDAO.deleteTempOrder(tempOrder.getId());//发货单生成后删除暂存信息；
            var resultt = shipDAO.update(order);
            if (resultt > 0) {
                truck.setState((short) 30);
                cardao.update(truck);
                task.setState((short) 2);
                task.setShipOrderSN(order.getSn());
                transTaskDao.update(task);
            }
        }
        orderList.add(order);
        //var data = shipDAO.queryByMergeSN(order.getSn());
        return orderList;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public WeightData Save(String dbSno, BigDecimal weight, String discern, boolean handlerType, boolean weighType, BigDecimal orgWeight, String handler, String carname, String stationType, String truckNum) {
        var result = new WeightData();
        try {
            if (handlerType) {//产品发货
                if (weighType) {//发货出厂
                    var ship = brickShipOrderDao.findByTruckPlate(truckNum, 0);
                    if (ship != null) {
                        ship.setGrossWeight(weight);
                        ship.setNetWeight(weight.subtract(ship.getTareWeight()));
                        ship.setState((short) 1);
                        ship.setOutTime(new Date());
                        var place = placeDao.findByTruckPlate(truckNum, 4);
                        if (place == null) {
                            result.setSaveResult(-7);
                            result.setMessage("车辆未确认出库，请联系库管");
                            return result;
                        }
                        ship.setContractSN(place.getContractSN());
                        ship.setCustomerSN(place.getCustomerSN());
                        ship.setCustomerName(place.getCustomerName());
                        ship.setPrintTitle(place.getAddress());
                        ship.setRemark(place.getRemark());
                        var contract = saleContractDao.findBySN(place.getContractSN());
                        if (contract != null) {
                            ship.setLinkerName(contract.getPrintTitle());
                            ship.setContractUnit(contract.getContractingUnit());
                            ship.setSalerName(contract.getSalerName());
                            var user = userDao.findBySN(contract.getSalerSN());
                            if (user != null) {
                                ship.setSalerPhone(user.getMobileNum());
                            }
                        }
                        if (place != null) {
                            var detail = detailDao.querySalePlaceSn(place.getSn());
                            var net = detail.stream().map(SaleOrderPlaceDetailEntity::getQuantity).reduce(BigDecimal::add).get();
                            var wc = net.multiply(BigDecimal.valueOf(0.005));
                            if (ship.getNetWeight().compareTo(new BigDecimal(10))>0) {
                                if (ship.getNetWeight().subtract(net).compareTo(BigDecimal.valueOf(0)) < 0 || ship.getNetWeight().subtract(net).compareTo(wc) > 0) {
                                    result.setSaveResult(-7);
                                    result.setMessage("重量超差，请核对发货数量");
                                    return result;
                                }
                            }else{
                                if(ship.getNetWeight().subtract(net).compareTo(BigDecimal.valueOf(0)) < 0){
                                    result.setSaveResult(-7);
                                    result.setMessage("重量超差，请核对发货数量");
                                    return result;
                                }
                            }
                            if (detail.size() > 0) {
                                ship.setSaleOrderSN(place.getSaleSN());
                                brickShipOrderDao.update(ship);
                                for (var i = 0; i < detail.size(); i++) {
                                    BrickShipOrderDetailEntity entity = new BrickShipOrderDetailEntity();
                                    entity.setState((short) 0);
                                    entity.setSn(queryNewSN(BrickShipOrderDetailEntity.class));
                                    entity.setOrderSN(ship.getSn());
                                    entity.setQuantity(detail.get(i).getQuantity());
                                    entity.setPackWeight(detail.get(i).getPackageWeight());
                                    entity.setPackageName(detail.get(i).getPackageName());
                                    entity.setAccountProductName(detail.get(i).getProductName());
                                    entity.setAccountProductSN(detail.get(i).getProductSN());
                                    entity.setAccountProductSpec(detail.get(i).getProductSpec());
                                    entity.setBillProductName(detail.get(i).getProductName());
                                    entity.setBillProductSpec(detail.get(i).getProductSpec());
                                    entity.setBillProductSN(detail.get(i).getProductSN());
                                    entity.setPackageSn(detail.get(i).getPackageSn());
                                    entity.setProductCate(detail.get(i).getProductCateName());
                                    entity.setProductCateSN(detail.get(i).getProductCateSn());
                                    entity.setProductName(detail.get(i).getProductName());
                                    entity.setProductSN(detail.get(i).getProductSN());
                                    entity.setProductSpec(detail.get(i).getProductSpec());
                                    entity.setQuantity(detail.get(i).getQuantity());
                                    entity.setVolume((detail.get(i).getQuantity().multiply(new BigDecimal(1000))).divide(detail.get(i).getPackageWeight(), RoundingMode.DOWN));
                                    entity.setWarehouseName(detail.get(i).getWareHouseName());
                                    entity.setWarehouseSn(detail.get(i).getWareHouseSN());
                                    entity.setShipmentReviewPrice(detail.get(i).getPrice());
                                    entity.setShipmentReviewMoney(detail.get(i).getMoney());
                                    brickShipOrderDetailDao.insertNew(entity);
                                }
                            } else {
                                result.setSaveResult(-7);
                                result.setMessage("未找到派车明细");
                                return result;
                            }
                            place.setState((short) 5);
                            place.setShiporder(ship.getSn());
                            placeDao.update(place);
                            result.setOrderType(1);
                            result.setOrderSNO(ship.getSn());
                            result.setSaveResult(1);
                            result.setMessage("无人值守车辆出场");
                            return result;
                        } else {
                            result.setSaveResult(-7);
                            result.setMessage("车辆未完成出库");
                            return result;
                        }
                    } else {
                        result.setSaveResult(-7);
                        result.setMessage("未找到车辆进场记录");
                        return result;
                    }
                } else {//存皮
                    var place = placeDao.findByTruckPlate(truckNum, 3);
                    if (place == null) {
                        throw new Exception("未找到该车辆订单信");
                    }
                    var ship = brickShipOrderDao.findByTruckPlate(truckNum, 0);
                    if (ship == null) {
                        ship = new BrickShipOrderEntity();
                        ship.setSn(queryNewSN(BrickShipOrderEntity.class));
                    }
                    ship.setContractSN(place.getContractSN());
                    ship.setCustomerSN(place.getCustomerSN());
                    ship.setCustomerName(place.getCustomerName());
                    ship.setState((short) 0);
                    ship.setBackTime(new Date());
                    ship.setCreateTime(new Date());
                    ship.setTareWeight(weight);
                    ship.setTruckPlate(truckNum);
                    var contract = saleContractDao.findBySN(place.getContractSN());
                    if (contract != null) {
                        ship.setLinkerName(contract.getPrintTitle());
                        ship.setContractUnit(contract.getContractingUnit());
                        ship.setSalerName(contract.getSalerName());
                        var user = userDao.findBySN(contract.getSalerSN());
                        if (user != null) {
                            ship.setSalerPhone(user.getMobileNum());
                        }
                    }
                    brickShipOrderDao.insertNew(ship);
                    result.setOrderType(1);
                    result.setMessage("保存成功");
                    result.setSaveResult(1);
                    result.setOrderSNO(ship.getSn());
                }
            } else {
                //原材入库
                PurchaseReceiptEntity receiptOrder;
                ProductShipOrderEntity shipOrderEntity;
                shipOrderEntity = shipDAO.findTruckOrderDraft(truckNum);
                receiptOrder = receiptDao.queryByTruckPlateByState(truckNum);
                if (weighType) {//二次过磅
                    var wxUsers = wechatDao.findByTruckPlate(truckNum, 0);
                    result.setSaveResult(-7);//原材出厂过皮
                    if (receiptOrder == null) {
                        result.setMessage("未找到车辆入厂信息信息");
                        return result;
                    }
                    if (receiptOrder.getCheckState() == 0 || Tl.isEmpty(receiptOrder.getWarehouseSN())) {
                        result.setMessage("原材未验收或未设置原材仓库");
                        return result;
                    }
                    if (receiptOrder.getCheckState() == -1) {
                        result.setMessage("验收不合格");
                        receiptOrder.setState((short) -1);
                        receiptOrder.setRemark("验收不合格");
                        if (weight.compareTo(receiptOrder.getGrossWeight()) > 0 && weight.subtract(receiptOrder.getGrossWeight()).compareTo(new BigDecimal(0.1)) >= 0) {
                            result.setSaveResult(-44);
                            result.setMessage((weight.subtract(receiptOrder.getGrossWeight())).toString() + "吨");
                        }
                        receiptOrder.setStationType(stationType);
                        receiptDao.update(receiptOrder);
                        return result;
                    }
                    var supplier = supplierDao.findBySN(receiptOrder.getSupplierSN());
                    if (supplier.getState() == -1) {
                        result.setMessage("供应商不可用");
                        return result;
                    }
                    receiptOrder.setTareWeight(weight);
                    receiptOrder.setOrgTareWeight(orgWeight);
                    var contract = purchaseContractDao.findBySN(receiptOrder.getContractSN());
                    if (contract != null) {
                        if (!Tl.isEmpty(contract.getDeductionType())) {
                            switch (contract.getDeductionType()) {
                                case "取整":
                                    receiptOrder.setNetWeight(receiptOrder.getGrossWeight().subtract(weight).setScale(0, RoundingMode.DOWN));
                                    break;
                                case "实际磅重":
                                    receiptOrder.setNetWeight(receiptOrder.getGrossWeight().subtract(weight));
                                    break;
                                case "减50公斤后四舍五入(保留1位小数)":
                                    receiptOrder.setNetWeight(receiptOrder.getGrossWeight().subtract(weight).subtract(receiptOrder.getBlockWeight()).subtract(BigDecimal.valueOf(0.05)).setScale(1, RoundingMode.HALF_UP));
                                    break;
                            }
                        } else {
                            receiptOrder.setNetWeight(receiptOrder.getGrossWeight().subtract(weight).subtract(receiptOrder.getBlockWeight()).subtract(BigDecimal.valueOf(0.05)).setScale(1, RoundingMode.HALF_UP));
                        }
                    } else {
                        receiptOrder.setNetWeight(receiptOrder.getGrossWeight().subtract(weight).subtract(receiptOrder.getBlockWeight()).subtract(BigDecimal.valueOf(0.05)).setScale(1, RoundingMode.HALF_UP));
                    }
                    if (receiptOrder.getNetWeight().compareTo(BigDecimal.ZERO) < 0) {
                        result.setMessage("净重不允许为负数");
                        result.setSaveResult(-44);
                        if (receiptOrder.getNetWeight().compareTo(new BigDecimal(0.3)) >= 0) {
                            result.setMessage(receiptOrder.getNetWeight().toString() + "吨");
                        }
                        return result;
                    }
                    receiptOrder.setPrintCount((short) 1);
                    receiptOrder.setPrintState(true);
                    receiptOrder.setState(OrderState.NORMAL.code);
                    receiptOrder.setOutTime(new Date());
                    receiptOrder.setAmount(receiptOrder.getPrice().multiply(receiptOrder.getNetWeight()));
                    var sss = receiptDao.update(receiptOrder);
                    if (sss > 0) {
                        if (wxUsers != null) {
                            wxUsers.setState(1);
                            wechatDao.update(wxUsers);
                        }
                        result.setSaveResult(sss);
                        writeLog(ActionType.UPDATE, receiptOrder.getSn(),
                                String.format("无人磅房原材入库地磅%s车辆%s称重%s吨出厂称重保存"
                                        , dbSno, truckNum, weight.toPlainString()), receiptOrder.toJson(), receiptOrder.getClass());
                    }
                    var inventory = inventoryDao.findByWHSNAndRmSN(receiptOrder.getWarehouseSN(), receiptOrder.getRmSN());
                    if (inventory == null) {
                        inventory = new RawMaterialInventoryEntity();
                        inventory.setQuantity(receiptOrder.getNetWeight());
                        inventory.setRmSN(receiptOrder.getRmSN());
                        inventory.setWhSN(receiptOrder.getWarehouseSN());
                        inventoryDao.insertNew(inventory);
                    } else {
                        var quantity = inventory.getQuantity();
                        inventory.setQuantity(receiptOrder.getNetWeight().add(inventory.getQuantity()));
                        inventoryDao.update(inventory);
                        writeLogs(ActionType.CREATE, inventory.getSn(), "创建入库单，库存增加" + receiptOrder.getNetWeight() + "由" + quantity + "变为" + inventory.getQuantity(), null, RawMaterialInventoryEntity.class);
                    }
                    var warehouse = warehouseDao.findBySN(receiptOrder.getWarehouseSN());
                    if (warehouse != null) {
                        warehouse.setInventory(warehouse.getInventory().add(receiptOrder.getNetWeight()));
                        warehouseDao.update(warehouse);
                        //writeLog(ActionType.UPDATE,warehouse.getSn(),"创建入库单，库存增加"+receiptOrder.getNetWeight()+"由"+quantity+"变为"+inventory.getQuantity(),null,RawMaterialInventoryEntity.class);
                    }
                    result.setOrderType(0);
                    result.setOrderSNO(receiptOrder.getSn());
                    result.setOrder(receiptOrder);
                    result.setMessage("称重已保存");
                } else {//进厂过毛
                    var wxUser = wechatDao.findByTruckPlate(truckNum, 0);
                    //原材入库暂存逻辑
                    String supplierSN = "", supplierName = "", rmSN = "", rmSpec = "", rmName = "", rmBrand = "",
                            rmCateSN = "", rmCateName = "", organizationCode = "", contractSN = "";
                    var interval = Tl.getInteger(HsApp.getSystemSet(CK.NoPersonWeight_RAWTruckIN_Interval));
                    if (interval > 0) {
                        var truckLastOrder = receiptDao.queryByTruckPlate(truckNum);
                        var now = (new Date()).getTime();
                        var last = (new Date()).getTime();
                        if (truckLastOrder != null) {
                            last = truckLastOrder.getInTime().getTime();
                        }
                        if ((now - last) <= (long) interval * 60 * 1000) {
                            result.setSaveResult(-7);
                            result.setMessage("同一辆车，" + interval + "分钟内不允许重复入库");
                            return result;
                        }
                    }
                    if (wxUser != null) {
                        var supplier = supplierDao.findBySN(wxUser.getSupplierSN());
                        if (supplier != null) {
                            supplierSN = supplier.getSn();
                            supplierName = supplier.getSupplierName();
                            contractSN = wxUser.getPurchaseContractSN();
                        }
                        rmSN = wxUser.getRmSN();
                        var rmInfo = rmDao.findBySN(rmSN);
                        if (rmInfo != null) {
                            rmSpec = rmInfo.getRmSpec();
                            rmName = rmInfo.getRmName();
                            rmBrand = rmInfo.getBrand();
                            var rmCate = rmCateDao.findBySN(rmInfo.getRmCateSN());
                            if (rmCate != null) {
                                rmCateName = rmCate.getCateName();
                                rmCateSN = rmCate.getSn();
                                organizationCode = rmCate.getOrganizationCode();
                            }
                        }
                    } else {
                        result.setSaveResult(-7);
                        result.setMessage("未找到注册信息");
                        return result;
                    }
                    var saveFlag = false;
                    if (receiptOrder == null) {
                        receiptOrder = new PurchaseReceiptEntity();
                        receiptOrder.setSn(queryNewSN(PurchaseReceiptEntity.class));
                        receiptOrder.setTruckPlate(truckNum);
                        receiptOrder.setInTime(new Date());
                        receiptOrder.setCreatorName(Tl.isEmpty(handler) ? "无人磅房" : handler);
                        saveFlag = true;
                    }
                    var purcontract = purchaseContractDao.findBySN(contractSN);
                    if (purcontract != null) {
                        receiptOrder.setContractingUnit(purcontract.getContractingUnit());
                    }
                    receiptOrder.setOrgWeight(wxUser.getWeight());
                    receiptOrder.setStationType(stationType);
                    receiptOrder.setOpenId(wxUser.getOpenId());
                    receiptOrder.setContractSN(contractSN);
                    receiptOrder.setOrganizationCode(organizationCode);
                    receiptOrder.setRmName(rmName);
                    receiptOrder.setBrand(rmBrand);
                    receiptOrder.setRmSpec(rmSpec);
                    receiptOrder.setRmSN(rmSN);
                    receiptOrder.setRmCate(rmCateName);
                    receiptOrder.setRmCateSN(rmCateSN);
                    receiptOrder.setSupplierName(supplierName);
                    receiptOrder.setSupplierSN(supplierSN);
                    receiptOrder.setGrossWeight(weight);
                    receiptOrder.setOrgGrossWeight(orgWeight);
                    receiptOrder.setPrintCount((short) 0);
                    receiptOrder.setPYFieldValue();
                    if (saveFlag) {
                        var ss = receiptDao.insertNew(receiptOrder);
                        result.setSaveResult(ss);
                    }
                    result.setOrderType(0);
                    result.setOrderSNO(receiptOrder.getSn());
                    result.setOrder(receiptOrder);
                    result.setMessage("称重已保存");
                }
            }
        } catch (Exception ee) {
            ee.printStackTrace();
            result.setMessage(ee.toString());
            result.setSaveResult(-7);
            log.error("无人磅房称重保存", ee);
        }
        return result;
    }

    @Override
    public Integer appendOrderPrintCount(int orderType, String orderID) {
        if (orderType == 0) {
            var receiptOrder = receiptDao.findBySN(orderID);
            if (receiptOrder != null) {
                receiptOrder.setPrintCount((short) (receiptOrder.getPrintCount() + 1));
                return receiptDao.update(receiptOrder);
            }
        } else {
            var shipOrder = shipDAO.findBySN(orderID);
            if (shipOrder != null) {
                shipOrder.setPrintcount(shipOrder.getPrintcount() + 1);
                return shipDAO.update(shipOrder);
            }
        }
        return 0;
    }

    IRawMaterialTransferDao rmTransDao;

    @Autowired
    public void setRmTransDao(IRawMaterialTransferDao rmTransDao) {
        this.rmTransDao = rmTransDao;
    }
}
